package edu.cuit.campus.company.controller;

import com.alibaba.fastjson2.JSONObject;
import edu.cuit.campus.commons.StringUtils;
import edu.cuit.campus.commons.annotations.Controller;
import edu.cuit.campus.commons.annotations.RequestMapping;
import edu.cuit.campus.commons.annotations.ResponseBody;
import edu.cuit.campus.commons.response.Result;
import edu.cuit.campus.company.service.CompanyService;
import edu.cuit.campus.company.service.bean.CompanyServiceBean;
import edu.cuit.campus.entity.po.Company;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/8/11 13:56
 */
@Controller
@RequestMapping("/companies")
public class CompanyController {
    private CompanyService service = new CompanyServiceBean();

    @RequestMapping("/register")
    @ResponseBody
    public Result register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String json = "";
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null)
            json += line;

        //调用业务模型
        if(!StringUtils.isBlank(json)){
            var company = JSONObject.parseObject(json, Company.class);
            var id = service.register(company);
            return id == null ? Result.fail("注册失败,请检查注册信息") : Result.ok();
        }

        return Result.fail("注册失败:未填写公司信息");
    }

    @RequestMapping("/list")
    @ResponseBody
    public Result list(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        var pageIndex = request.getParameter("pageIndex") == null ? 1 : Integer.parseInt(request.getParameter("pageIndex"));
        var pageSize = request.getParameter("pageSize") == null ? 10 : Integer.parseInt(request.getParameter("pageSize"));
        var page = service.list(pageIndex, pageSize);
        return Result.ok(page);
    }
}
